/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package control.boo;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Jojo
 */
public class LejosFileMerger {
    File inputfile;
    String inputfileAsString = "";
    String className = "";
    
    File outputfile;
    String outputfileAsString = "";
    
    LejosFileMerger(File pFile){
        this.inputfile = pFile;
        this.className = this.inputfile.getName().replaceAll(".java", "");
        File parent = new File(inputfile.getParent()+File.separator+".tmp");
        parent.mkdir();        
        this.outputfile = new File(parent.getAbsolutePath()+File.separator+inputfile.getName());
        try {
            this.outputfile.createNewFile();
        } catch (IOException ex) {
            Logger.getLogger(LejosFileMerger.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    
    
    void buildTheWholeSourceCode(){
        this.addClassHead();
        this.addUserCode();
        this.addMainMethodAndClassFoot();
        this.writeTheCodeToFile();
    }

    private void addClassHead() {
        this.outputfileAsString = "public class "+this.className+" { \n \n";
    }

    private void addUserCode() {
        try {
            Scanner s = new Scanner(this.inputfile);
            inputfileAsString = s.useDelimiter("\\Z").next();
            s.close();
            
            outputfileAsString = outputfileAsString.concat(inputfileAsString);
            
        } catch (FileNotFoundException ex) {
            Logger.getLogger(LejosFileMerger.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("LejosFileMerger Error: addUserCode : File not found");
        }
    }

    private void addMainMethodAndClassFoot() {
        outputfileAsString = outputfileAsString.concat("\n\n\tpublic void main(String[] args){\n"
                + "\t\tnew "+this.className+"().start();\n"
                + "\t}\n\n}");
    }

    private void writeTheCodeToFile() {
        PrintStream out = null;
        try {
            out = new PrintStream(new FileOutputStream(this.outputfile.getAbsolutePath()));
            out.print(this.outputfileAsString);
        }
        catch(Exception e){
            System.out.println("LejosFileMerger Error: writeTheCodeToFile : File not found");
        }
        finally {
             if(out != null){ out.close();}
        }
   }
    
    
    
}
